package cn.geminis.task.executor.service;

import cn.geminis.task.executor.entity.HttpJobParam;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * @author puddi
 */
@Service
@Slf4j
public class GeminisExecutor {

    @XxlJob("httpJobHandler")
    public void httpJobHandler() {
        try (var client = HttpClients.createDefault()) {
            var paramStr = XxlJobHelper.getJobParam();
            var param = JSONObject.parseObject(paramStr, HttpJobParam.class);

            var host = HttpHost.create(param.getUrl());
            var requestBuilder = RequestBuilder
                    .create(param.getMethod());
            for (var header : param.getHeaders()) {
                requestBuilder.addHeader(header);
            }
            if (StringUtils.hasText(param.getBody())) {
                requestBuilder.setEntity(new NStringEntity(param.getBody(), ContentType.parse(param.getContentType())));
            }
            var request = requestBuilder.build();

            try (var response = client.execute(host, request)) {
                var body = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
                XxlJobHelper.log(body);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    XxlJobHelper.handleSuccess();
                } else {
                    XxlJobHelper.handleFail(response.getStatusLine().getReasonPhrase());
                }
            }
        } catch (IOException e) {
            XxlJobHelper.log(e);
            XxlJobHelper.handleFail();
        }
    }

}
